#!/usr/bin/python3
# -*- coding: utf-8 -*-

from coreweb import get, post
from datetime import datetime
from sqlalchemy import func

import db, re

_RE_EMAIL = re.compile(
    r'^[a-z0-9\.\-\_]+\@[a-z0-9\-\_]+(\.[a-z0-9\-\_]+){1,4}$')
_RE_SHA1 = re.compile(r'^[0-9a-f]{40}$')

@get('/users', 'users.html')
async def users(*, request, page=1,page_size=5):
    session = db.create_session()
    page_index = int(page)
    total = session.query(func.count(db.User.id)).scalar()
    pages = (total - 1) // page_size + 1
    if pages > 0:
        result = [user for user in session.query(db.User).filter().limit(page_size).offset((page_index-1)*page_size)]
        if pages <= 5:
            page_list = range(1, pages + 1)
        else:
            if page_index > 3 and page_index < pages - 3:
                page_list = range(page_index - 2, page_index + 3)
            if page_index <= 3:
                page_list = range(1, 6)
            if page_index < pages - 3:
                page_list = range(pages -5, pages + 1)
        pre = {
            'status': page_index > 1, 
            'num': page_list[0] - 1 if page_list[0] - 1 > 0 else 1
        }
        next = {
            'status': page_index < pages, 
            'num': page_list[-1] + 1 if page_list[-1] + 1 <= pages else pages
        }
        data = {"users": result, 'page': {'index': page_index, 'pages': pages, 'total': total, 'pre': pre, 'next': next, 'list': page_list}}
    else:
        data = {'users': None, 'page': None}
    return data

@get('/user/edit', 'user_edit.html')
async def user_edit():
    return {}

@get('/user/edit/{id}', 'user_edit.html')
async def user_edit_id(*, id, request):
    session = db.create_session()
    user = session.query(db.User).filter_by(id=id).first()
    return {'user': user}

@post('/user/delete/{id}')
async def user_delete_id(*, id, request):
    session = db.create_session()
    user = session.query(db.User).filter_by(id=int(id)).first()
    user = request.__user__
    if user and (user.admin or user.user_id == user.id):
        session.delete(user)
        session.commit()
    else:
        return {'code': -1, 'msg': '没有删除该user的权限'}
    return {'code': 0, 'msg': '删除成功'}

@post('/user/save')
async def do_user_edit(*, name, email, admin, password, image, id, request):
    if not name or not name.strip():
        return {'code': -1, 'field': 'name', 'msg': 'name is null'}
    if not password or not _RE_SHA1.match(password):
        return {'code': -1, 'field': 'password', 'msg': 'password is null'}
    # if not image or not image.strip():
    #     return {'code': -1, 'field': 'image', 'msg': 'image is null'}
    session = db.create_session()
    if not id or not id.strip() or id.isdigit():
        # 修改 
        user = session.query(db.User).filter_by(name=name).first()
        if user and user.id != int(id):
            return {'code': -1, 'field': 'email', 'msg': '用户名已注册'}
        user = session.query(db.User).filter_by(id=int(id)).first()
        if user.email != email:
            return {'code': -1, 'field': 'email', 'msg': 'email can not modify'}
        user.name = name
        user.email = email
        user.admin = admin
        user.password = password
        user.image = image
        user.updated_at = datetime.now()
        session.commit()
    else:
        # 新增
        if not email or not _RE_EMAIL.match(email):
            return {'code': -1, 'field': 'email', 'msg': 'email 格式不正确'}
        user = session.query(db.User).filter_by(email=email).first()
        if user:
            return {'code': -1, 'field': 'email', 'msg': '邮箱已注册'}
        user = session.query(db.User).filter_by(name=name).first()
        if user:
            return {'code': -1, 'field': 'email', 'msg': '用户名已注册'}
        user = db.User(name=name, email=email, admin=admin, password=password, image=image)
        session.add(user)
        session.commit()
    data = {'code': 0, 'msg': '编辑成功'}
    return data